package base.core.security.dms;

import base.core.api.Result;
import base.core.log.LogAspect;
import base.core.util.Utils;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 鉴权失败的返回处理
 */
@Slf4j
@Component
public class DmsUnAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {


    /**
     * 当用户尝试访问安全的REST资源而不提供任何凭据时，将调用此方法发送401 响应
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        //打印错误日志
        StringBuffer buffer = new StringBuffer();
        buffer.append("\n");
        buffer.append("╔═════════════════════════════════════════════════════════════════").append("\n");
        buffer.append(Utils.format("    访问权限错误:"));
        buffer.append(Utils.format("    {} 发起 {} 请求: {} ", LogAspect.getIP(request), request.getMethod(), request.getRequestURI())).append("\n");
        buffer.append("╚═════════════════════════════════════════════════════════════════");
        buffer.append("\n");

        log.error(buffer.toString());

        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        String errorMsg = objectMapper.writeValueAsString(Result.failed().setMsg(authException.getMessage()).setCode(HttpServletResponse.SC_UNAUTHORIZED));
        out.write(errorMsg);
        out.flush();
        out.close();
    }
}
